package com.example.ren.template;

import android.app.Application;
import android.content.Context;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.https.HttpsUtils;

import greendao.DaoMaster;
import greendao.DaoSession;
import greendao.GreenDaoUpgradeHelper;
import okhttp3.OkHttpClient;
import utils.ActivityManager;


/**
 * Created by Ren on 2017/12/4.
 */

public class App extends Application {

    public static String APP_NAME = "app_name";
    private static App mApp;
    private static DaoSession mDaoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        initApp();
        initDB();
        initOkHttp();
    }

    //初始化mApp
    private void initApp() {
        mApp = this;
    }

    static public App getApp() {
        return mApp;
    }

    /**
     * 初始化数据库 数据库名称
     */
    private void initDB() {
        GreenDaoUpgradeHelper devOpenHelper = new GreenDaoUpgradeHelper(App.getApp(), APP_NAME + "db", null);
        DaoMaster mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        mDaoSession = mDaoMaster.newSession();
    }

    /**
     * 初始化okhttp网络
     * 暂时取消了https的证书验证，允许登录所有网站
     */

    private void initOkHttp() {
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .hostnameVerifier(new HttpsUtils.UnSafeHostnameVerifier())
                //其他配置
                .build();
        OkHttpUtils.initClient(okHttpClient);
    }

    /**
     * 获取数据库操作对象
     * */

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    /**
     * 退出App
     * @param context
     * */
    public void exitApp(Context context) {
        ActivityManager.getInstance().killAllActivity();
        ActivityManager.getInstance().AppExit(context);
    }

}
